Python realizes the method of turning photos into cartoon pictures [Based on opencv]

  • 2020-07-21 08:41:03
  • OfStack

This article illustrates how Python can turn photos into cartoon images. To share for your reference, specific as follows:

The previous article covered using Photoshop to turn photos into cartoon images, but this time it's done in code that probes the internals of various filters.

Production environment: Windows10, Python 2.7, Anaconda

Task description: Cartoonize all images in a folder of D disk with code, and then save them to another folder.

As mentioned above, the key to cartooning is to strengthen the edges and reduce the color, so Photoshop USES filters to illuminate the edges and dry strokes. When you work with images in code, you're also dealing with edges and colors. The OpenCV library is used for photo manipulation in four steps.

1. Apply a bilateral filter to reduce the color of the image
2. Convert the color image to gray, and apply the median filter to reduce the image noise
3. Use adaptive thresholds to process grayscale images to create profiles
4. Overlay the color image from Step 1 with the outline from Step 3

Step 1: Reduce image color

Because bilateral filters smooth flat areas while maintaining sharp edges, they are ideal for converting RGB images into cartoons. Although the speed seems to be a bit slower one technique is repetition (for example, using num_bilateral = 77 times) to apply a small bilateral filter instead of just one large bilateral filter.


import cv2
num_down = 2  #  Reduce the number of pixel samples 
num_bilateral = 7 #  Defines the number of bilateral filters 
img_rgb = cv2.imread("img_example.jpg")
#  Lower the sample with a Gaussian pyramid 
img_color = img_rgb
for _ in xrange(num_down):
 img_color = cv2.pyrDown(img_color)
#  The small bilateral filtering is reused instead 1 Big filter 
for _ in xrange(num_bilateral):
 img_color = cv2.bilateralFilter(img_color, d=9,
         sigmaColor=9,
         sigmaSpace=7)
#  Raise the sample image to its original size 
for _ in xrange(num_down):
 img_color = cv2.pyrUp(img_color)

cv2.bilateralFilter Three parameters control the diameter of the pixel neighborhood (d) and the standard deviation of the filter in the color space (sigmaColor) and the coordinate space (sigmaSpace).

Step 2: Convert to grayscale and use a median filter to reduce the noise

OpenCV offers a variety of options for edge detection, and the advantage of adaptive threshold processing is that it can detect the most prominent features in each small area of the image, independent of the overall attributes of the image.

Apply a median filter to reduce the color of the image. The original color image is converted to grayscale image and median blur is applied to reduce the noise in the grayscale image.


#  Convert to grayscale and make it moderately fuzzy 
img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_RGB2GRAY)
img_blur = cv2.medianBlur(img_gray, 7)

Step 3: Create the outline

After noise reduction, adaptive thresholds can be safely applied to create profiles. Even if there is 1 image noise, blockSize = 9 cv2.ADAPTIVE_THRESH_MEAN_C The algorithm also ensures that the threshold is applied to the average of the 9x9 neighborhood minus C = 2.


#  Edge detected and enhanced 
img_edge = cv2.adaptiveThreshold(img_blur, 255,
         cv2.ADAPTIVE_THRESH_MEAN_C,
         cv2.THRESH_BINARY,
         blockSize=9,
         C=2)

Step 4: Combine Outlines with color images

The last step is to combine the processed color image (img_color) with the edge mask (img_edge). At this point, 1 can be cartoon image of the original code was written. The picture effect is a little bit of science and technology aesthetic, not artistic enough, the effect lost to Photoshop, but in the efficiency of one city.


#  Convert back to color image 
img_edge = cv2.cvtColor(img_edge, cv2.COLOR_GRAY2RGB)
img_cartoon = cv2.bitwise_and(img_color, img_edge)
#  Display images 
cv2.imshow("cartoon", img_cartoon)

Finally, the above code is encapsulated as a function. Import the os module for python to facilitate file processing.


# -*- coding: utf-8 -*-
import cv2
import os
def cartoonise(picture_name):
 imgInput_FileName = picture_name
 imgOutput_FileName = "D:\pythonpractice\CartoonImage\cartoon" + picture_name
 num_down = 2   # Reduce the number of pixel samples 
 num_bilateral = 7 # Defines the number of bilateral filters 
 img_rgb = cv2.imread(imgInput_FileName)  # Read the pictures 
 # Lower the sample with a Gaussian pyramid 
 img_color = img_rgb
 for _ in xrange(num_down):
  img_color = cv2.pyrDown(img_color)
 # The small bilateral filtering is reused instead 1 Big filter 
 for _ in xrange(num_bilateral):
  img_color = cv2.bilateralFilter(img_color,d=9,sigmaColor=9,sigmaSpace=7)
 # Raise the sample image to its original size 
 for _ in xrange(num_down):
  img_color = cv2.pyrUp(img_color)
 # Convert to grayscale and make it moderately blurry 
 img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_RGB2GRAY)
 img_blur = cv2.medianBlur(img_gray, 7)
 # Edge detected and enhanced 
 img_edge = cv2.adaptiveThreshold(img_blur,255,
          cv2.ADAPTIVE_THRESH_MEAN_C,
          cv2.THRESH_BINARY,
          blockSize=9,
          C=2)
 # Convert back to color image 
 img_edge = cv2.cvtColor(img_edge, cv2.COLOR_GRAY2RGB)
 img_cartoon = cv2.bitwise_and(img_color, img_edge)
 #  Save the converted image 
 cv2.imwrite(imgOutput_FileName, img_cartoon)
ImageList = [] # Set up empty List
# Loop reads "D:\pythonpractice\Image" Filename in 
for filename in os.listdir(r"D:\pythonpractice\Image"):
 ImageList.append(filename)  # Add the file name to ImageList
for i in ImageList: # Loop reads ImageList In the file name, it will be a cartoon processing 
 print(" Cartoonize " + i)
 cartoonise(i)

More about Python related content interested readers to view this site project: Python pictures skills summary, "Python data structure and algorithm tutorial", "Python Socket programming skills summary", "Python function using techniques", "Python string skills summary", "Python introduction and advanced tutorial" and "Python file and directory skills summary"

I hope this article has been helpful in Python programming.


Related articles: